package com.fy.tt.executor.environment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fy.tt.permission.PolicyAddModel;
import com.fy.tt.permission.PolicyCheckModel;
import com.fy.tt.utils.BandCore;

public class PolicyWorker {

    private String httpurl = "http://127.0.0.1:8083/";
    private String checkPath="permissionBus/policyPermission/checkPolicy";
    private String addPath="permissionBus/policyPermission/addPolicy";
    public PolicyWorker() {

    }

    public boolean addPolicy(PolicyAddModel policyAddModel){
        System.out.println("policy = " + policyAddModel.toString());
        String res= BandCore.doPost(httpurl+addPath, policyAddModel);
        JSONObject jsonObject = JSON.parseObject(res);
        if (res==null) {
            throw new RuntimeException("请求权限总线出错" );
        }else{
            return (boolean)jsonObject.get("success");
        }
    }

    //0表示不允许，-1表示禁止，1表示允许
    public Integer checkPolicy(PolicyCheckModel policyCheckModel){
        boolean toolCheckRes;
        policyCheckModel.setOperation("cannot.act");
        String url = httpurl+checkPath;
        String res= BandCore.doPost(url, policyCheckModel);
        System.out.println("res = " + res);;
        JSONObject jsonObject = JSON.parseObject(res);
        if ((boolean)jsonObject.get("success") == false) {
            throw new RuntimeException("请求权限总线出错" );
        }
        JSONObject data = (JSONObject)jsonObject.get("data");
        Boolean policyMatch=(Boolean)data.get("policyMatch");
        System.out.println("policyMatch = " + policyMatch);
        if(policyMatch){//被禁止
            return -1;
        }else{
            policyCheckModel.setOperation("can.act");
            res= BandCore.doPost(url,policyCheckModel);
            jsonObject = JSON.parseObject(res);
            data = (JSONObject)jsonObject.get("data");
            toolCheckRes= (boolean) data.get("policyMatch");
            if(toolCheckRes){
                return 1;
            }else{
                return 0;
            }
        }
    }

}

